package com.example.demo.service.multi;

import com.example.demo.db1.mapper.MyTableMapper1;
import com.example.demo.db2.mapper.MyTableMapper2;
import com.example.demo.entity.MyTable;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author yfy2001
 * @date 2024/6/11 9:04
 */
@Service
@Slf4j
public class MultiThreadQueryService {

    @Resource
    private MyTableMapper1 myTableMapper1;

    @Resource
    private MyTableMapper2 myTableMapper2;


    @Async("AsyncExecutor")
    public CompletableFuture<List<MyTable>> asyncQuery(Integer id) throws ExecutionException, InterruptedException {
        List<MyTable> result = new ArrayList<>();
        List<CompletableFuture<List<MyTable>>> futures=new ArrayList<>();
        log.warn("start query");
        String[] tables1 = {"t1", "t2", "t3", "t4", "t5"};
        for (String table : tables1) {
            CompletableFuture<List<MyTable>> future=
                    CompletableFuture.supplyAsync(()->myTableMapper1.selectListFromTableById(table,id));
            futures.add(future);
        }

        String[] tables2 = {"ta1", "ta2", "ta3", "ta4", "ta5"};
        for (String table : tables2) {
            CompletableFuture<List<MyTable>> future=
                    CompletableFuture.supplyAsync(()->myTableMapper2.selectListFromTableById(table,id));
            futures.add(future);
        }
        //每个线程要做的操作
        CompletableFuture<Void> allFuture=CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
        allFuture.join();
        for (CompletableFuture<List<MyTable>> future : futures) {
            result.addAll(future.get());
        }
        log.warn("end query");
        return CompletableFuture.completedFuture(result);
    }
}
